package com.ruoyi.face.controller;


import com.ruoyi.Outsider.domain.Outsider;
import com.ruoyi.Outsider.service.IOutsiderService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.inhabitant.domain.inhabitant;
import com.ruoyi.inhabitant.service.IinhabitantService;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.iai.v20200303.IaiClient;
import com.tencentcloudapi.iai.v20200303.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.util.Base64Utils;

import static com.ruoyi.common.core.domain.AjaxResult.*;


/**
 * @author zhangbaiyan
 * @date 2024-07-04 20:54
 * @description:测试
 * @version: 1.0
 */
@Anonymous
@RestController
@RequestMapping("/face/face")
public class FaceController {

    @Autowired
    private IOutsiderService outsiderService;
    @Autowired
    private IinhabitantService inhabitantService;

    @PostMapping("/FaceData")
    public AjaxResult test(@RequestParam("file") MultipartFile file) {


        try {
            // 打印接收到的文件信息
//            System.out.println("文件名称: " + file.getOriginalFilename());
//            System.out.println("文件大小: " + file.getSize() + " bytes");
            // 将MultipartFile转换为Base64编码
            byte[] fileBytes = file.getBytes();
            String base64Encoded = Base64Utils.encodeToString(fileBytes);

            try{
                // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
                // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
                // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
                Credential cred = new Credential("AKIDRrAIOKE3iDupouLyiTNOUnB06slvKiN6", "5ADBPafZO6jHmATzjZasDQdosyvtngRF");
                // 实例化一个http选项，可选的，没有特殊需求可以跳过
                HttpProfile httpProfile = new HttpProfile();
                httpProfile.setEndpoint("iai.tencentcloudapi.com");
                // 实例化一个client选项，可选的，没有特殊需求可以跳过
                ClientProfile clientProfile = new ClientProfile();
                clientProfile.setHttpProfile(httpProfile);
                // 实例化要请求产品的client对象,clientProfile是可选的
                IaiClient client = new IaiClient(cred, "ap-shanghai", clientProfile);
                // 实例化一个请求对象,每个接口都会对应一个request对象
                DetectLiveFaceRequest req = new DetectLiveFaceRequest();

                req.setImage(base64Encoded);
                // 返回的resp是一个DetectLiveFaceResponse的实例，与请求对象对应
                DetectLiveFaceResponse resp = client.DetectLiveFace(req);
                // 输出json格式的字符串回包
                System.out.println(AbstractModel.toJsonString(resp));
//                检测活体
//                if (resp.getScore()<80)return success("验证不成功");

                try{
                    Outsider outsider = new Outsider();
                    inhabitant inhabitant=new inhabitant();
                   List<Outsider> list= outsiderService.selectOutsiderList(outsider);
                    List<inhabitant> list2 = inhabitantService.selectinhabitantList(inhabitant);
                   int n = 0;
                   long id=0;
                   int b=0;
                    for (Outsider outsider1 : list) {
                        // 在这里处理outsider对象
                        FileInputStream inputStream = null;
//                        判断当前对象访问是否有权限
                        if (outsider1.getPermit()==1||outsider1.getPermit()==2)continue;
//                        判断对象是否在访问时间内
                        Date beginTime = outsider1.getBeginTime();
                        Date endTime = outsider1.getEndTime();
                        Calendar beginCal = Calendar.getInstance();
                        Calendar endCal = Calendar.getInstance();
                        beginCal.setTime(beginTime);
                        endCal.setTime(endTime);
                        Calendar nowCal = Calendar.getInstance();
                        if (!(beginCal.before(nowCal)&&endCal.after(nowCal))) continue;
                        String path = outsider1.getFaceImg();
                        path=path.substring(8);
                        String base64Strr = null;
                        try {
                            Base64.Encoder encoder = Base64.getEncoder();
                            inputStream = new FileInputStream("D:/ruoyi/uploadPath"+path);
                            int available = inputStream.available();
                            byte[] bytes = new byte[available];
                            inputStream.read(bytes);
                            String base64Str = encoder.encodeToString(bytes);
//                            System.out.println(base64Str);
                            base64Strr=base64Str;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }finally {
                            inputStream.close();
                        }
// 实例化一个请求对象,每个接口都会对应一个request对象
                        CompareFaceRequest reqs = new CompareFaceRequest();
                        reqs.setImageA(base64Encoded);
                        reqs.setImageB(base64Strr);
                        // 返回的resp是一个CompareFaceResponse的实例，与请求对象对应
                        CompareFaceResponse resps = client.CompareFace(reqs);
                        // 输出json格式的字符串回包
//                        System.out.println(AbstractModel.toJsonString(resps));
                        //验证通过
                        if (resps.getScore()>80){
                            n++;
                            id=outsider1.getId();
                            b=1;
                        }



                    }

                    if (b==0){
                        for (inhabitant inhabitant1 : list2) {
                            // 在这里处理outsider对象
                            FileInputStream inputStream = null;
                            String path = inhabitant1.getFaceImg();
                            path = path.substring(8);
                            String base64Strr = null;
                            try {
                                Base64.Encoder encoder = Base64.getEncoder();
                                inputStream = new FileInputStream("D:/ruoyi/uploadPath" + path);
                                int available = inputStream.available();
                                byte[] bytes = new byte[available];
                                inputStream.read(bytes);
                                String base64Str = encoder.encodeToString(bytes);
//                            System.out.println(base64Str);
                                base64Strr = base64Str;
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                inputStream.close();
                            }
// 实例化一个请求对象,每个接口都会对应一个request对象
                            CompareFaceRequest reqs = new CompareFaceRequest();
                            reqs.setImageA(base64Encoded);
                            reqs.setImageB(base64Strr);
                            // 返回的resp是一个CompareFaceResponse的实例，与请求对象对应
                            CompareFaceResponse resps = client.CompareFace(reqs);
                            // 输出json格式的字符串回包
//                        System.out.println(AbstractModel.toJsonString(resps));
                            //验证通过
                            if (resps.getScore() > 80) {
                                n++;
                                id = inhabitant1.getId();
                                b = 2;
                            }
                        }
                    }
                    if (n>0){
                        if (b==1){return success("验证成功",outsiderService.selectOutsiderById(id));
                        } else if (b==2) {
                            return success("验证成功",inhabitantService.selectinhabitantById(id));
                        }

                    }else{
                        return success("验证不成功");
                    }


                } catch (TencentCloudSDKException e) {
                    System.out.println(e.toString());
                }


            } catch (TencentCloudSDKException e) {
                System.out.println(e.toString());
            }





            // 打印Base64编码的文件内容
//            System.out.println("Base64 Encoded File Content: " + base64Encoded);

            // 这里可以添加更多的处理逻辑，比如保存到数据库或其他操作

            return success();
        } catch (IOException e) {
            // 更好的错误处理，避免在生产环境中使用e.printStackTrace()
            return success() ;
        }
    }
}
